/**
 * 
 */
package com.airlines.common;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.airlines.base.entity.dict.Select2;

import cn.mercury.utils.JsonUtils;

/**
 * @author panyannan
 * @date 2017年4月11日
 * @company XXXX Airlines
 * @description select2插件的工具类
 */
public class Select2Util {


	private static final Logger logger = LoggerFactory.getLogger(Select2Util.class);

	public static final String EMPTY_STRING = "";
	//空字符串返回前台的提示
	public static final String EMPTY_MSG = "未查询到数据";
	
	/**
	 * 将list对象转换为select2需要的json对象，如果没有数据，则返回用户 无查询结果 的提示
	 * @param list
	 * @param valueName
	 * @param lableName
	 * @return
	 */
	public static <T> String toJosn(List<T> list, String valueName, String lableName){
		List<Select2> select2List = new ArrayList<>();
		if(list !=null && list.size()>0){
			
			 for(T t: list){
				 
				 Select2 select2 = new Select2();
				 
				 String id = null;
				 String text = null;
//				try {
					id = String.valueOf(BeanFiledUtils.getFieldValueByName(valueName, t));
					text = String.valueOf(BeanFiledUtils.getFieldValueByName(lableName, t).toString());
					if(StringUtils.isNotBlank(id) && StringUtils.isNotBlank(text)){
						select2.setId(id);
						select2.setText(text);
						select2List.add(select2); 
					}
//				} catch (IllegalAccessException e) {
//					TraceUtil.error(logger, e);
//				} catch (InvocationTargetException e) {
//					TraceUtil.error(logger, e);
//				} catch (NoSuchMethodException e) {
//					TraceUtil.error(logger, e);
//				}catch (Exception e) {
//					TraceUtil.error(logger, e);
//				}
				 
			 }
		
		}else{
			 Select2 select2 = new Select2();
			 select2.setId(EMPTY_STRING);
			 select2.setText(EMPTY_MSG);
			 select2List.add(select2);
		}
		
		return JsonUtils.toJson(select2List);
	}
	
	/**
	 * 返回未查询到数据的提示
	 * @return
	 */
	public static String getEmptyJson() {
		Select2 select2 = new Select2();
		select2.setId(EMPTY_STRING);
		select2.setText(EMPTY_MSG);

		List<Select2> select2List = new ArrayList<>();
		select2List.add(select2);

		Map<String, Object> map = new HashMap<>();
		map.put("items", select2List);
		map.put("itemsCount", select2List.size());
		return JsonUtils.toJson(select2List);
	}
	

}
